﻿using System;
using System.Globalization;
using System.Windows.Forms;
using SGLLv2.UI.Properties;

namespace SGLLv2.UI
{
    public partial class FormCalls : Template.FormTemplate, IMethods
    {
        // Declare Global Variables
        private MDIParent mdiParent;
        private long? _callID;

        // Class Constructor
        public FormCalls()
        {
            InitializeComponent();
        }

        // Form
        private void FormCalls_Load(object sender, EventArgs e)
        {
            // Declare Local Variables
            mdiParent = (MDIParent)(ParentForm);
            if (mdiParent == null) return;

            try
            {
                // Fill out each dataset.
                sP_ROUTES_SELECTTableAdapter.Fill(dataSetSGLL.SP_ROUTES_SELECT);
                sP_DOCTORS_SELECTTableAdapter.Fill(dataSetSGLL.SP_DOCTORS_SELECT);
                sP_USERS_SELECTTableAdapter.Fill(dataSetSGLL.SP_USERS_SELECT);
                sP_USERS_SELECT_SPECIALTableAdapter.Fill(dataSetSGLL.SP_USERS_SELECT_SPECIAL);

                // Clear form
                ClearForm();

                // Removed preselected Filter ComboBoxes.
                comboBoxOpenByUserFilter.SelectedIndex = -1;
                comboBoxCloseByUserFilter.SelectedIndex = -1;
                comboBoxDoctorFilter.SelectedIndex = -1;
                comboBoxRouteFilter.SelectedIndex = -1;

                // Set maximum date for date time pickers
                dateTimePickerFilterStart.MaxDate = dateTimePickerFilterEnd.MaxDate = DateTime.Today;

                // Show calls
                RefreshCalls();

                // Prevent from calling future times the Call Form
                mdiParent.toolStripMenuItemCalls.Enabled = mdiParent.toolStripButtonCalls.Enabled = false;

                // Hooking Up Events
                dateTimePickerFilterStart.ValueChanged += dateTimePickerFilterStart_ValueChanged;
                dateTimePickerFilterEnd.ValueChanged += dateTimePickerFilterEnd_ValueChanged;
            }
            catch (Exception exception)
            {
                // Report Error
                mdiParent.SetMessage(MDIParent.MessageType.Error, exception.Message);
                Utilities.ExceptionManager(exception);
            }
        }
        
        // Text Boxes
        private void textBoxComments_KeyDown(object sender, KeyEventArgs e)
        {
            // Validate if is F5 Key.
            if (!e.KeyCode.Equals(Keys.F5)) return;

            // Add date time to the comment textbox.
            if ((textBoxComments.Text.Length + DateTime.Now.ToString(CultureInfo.InvariantCulture).Length) >= textBoxComments.MaxLength) return;
            textBoxComments.Text += string.Concat(DateTime.Now, " ");
            textBoxComments.SelectionStart = textBoxComments.Text.Length;
        }

        // Buttons
        private void buttonDoctor_Click(object sender, EventArgs e)
        {
            // Show Search Dialog Box
            SearchDialog.SearchDialog searchDialog = new SearchDialog.SearchDialog(dataSetSGLL.SP_DOCTORS_SELECT, Resources.SearchDialogBoxTitleDoctors);
            if (searchDialog.ShowDialog().Equals(DialogResult.Cancel)) return;
            comboBoxDoctor.SelectedValue = searchDialog.SelectedRow.Cells[0].Value.ToString();
            comboBoxDoctor.SelectedText = searchDialog.SelectedRow.Cells[1].Value.ToString();

            // Enable Save Button Function
            EnableButtonSave();
        }
        private void buttonDoctorFilter_Click(object sender, EventArgs e)
        {
            SearchDialog.SearchDialog searchDialog = new SearchDialog.SearchDialog(dataSetSGLL.SP_DOCTORS_SELECT, Resources.SearchDialogBoxTitleDoctors);
            if (searchDialog.ShowDialog().Equals(DialogResult.Cancel)) return;
            comboBoxDoctorFilter.SelectedValue = searchDialog.SelectedRow.Cells[0].Value.ToString();
            comboBoxDoctorFilter.SelectedText = searchDialog.SelectedRow.Cells[1].Value.ToString();

            // Enable Save Button Function
            RefreshCalls();
        }

        //CheckBoxes
        private void checkBoxRequets_CheckedChanged(object sender, EventArgs e)
        {
            EnableButtonSave();
        }

        // Data Grid View
        private void dataGridView_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            // Validation
            if (dataGridView.CurrentRow == null) return;

            // Prevent unwanted calls
            checkBoxSample.CheckedChanged -= checkBoxRequets_CheckedChanged;
            checkBoxShipping.CheckedChanged -= checkBoxRequets_CheckedChanged;
            checkBoxResult.CheckedChanged -= checkBoxRequets_CheckedChanged;
            checkBoxVials.CheckedChanged -= checkBoxRequets_CheckedChanged;
            checkBoxPromotional.CheckedChanged -= checkBoxRequets_CheckedChanged;
            checkBoxPrices.CheckedChanged -= checkBoxRequets_CheckedChanged;
            checkBoxVisit.CheckedChanged -= checkBoxRequets_CheckedChanged;
            checkBoxCopy.CheckedChanged -= checkBoxRequets_CheckedChanged;

            // Coding
            comboBoxOpenByUser.Text = dataGridView[usuarioDataGridViewTextBoxColumn.Index, e.RowIndex].Value.ToString();
            comboBoxDoctor.SelectedIndex = comboBoxDoctor.FindStringExact(dataGridView[doctorDataGridViewTextBoxColumn.Index, e.RowIndex].Value.ToString());
            checkBoxSample.Checked = Convert.ToBoolean(dataGridView[muestraDataGridViewCheckBoxColumn.Index, e.RowIndex].Value);
            checkBoxShipping.Checked = Convert.ToBoolean(dataGridView[envíoDataGridViewCheckBoxColumn.Index, e.RowIndex].Value);
            checkBoxResult.Checked = Convert.ToBoolean(dataGridView[resultadoDataGridViewCheckBoxColumn.Index, e.RowIndex].Value);
            checkBoxVials.Checked = Convert.ToBoolean(dataGridView[vialesDataGridViewCheckBoxColumn.Index, e.RowIndex].Value);
            checkBoxPromotional.Checked = Convert.ToBoolean(dataGridView[promociónDataGridViewCheckBoxColumn.Index, e.RowIndex].Value);
            checkBoxPrices.Checked = Convert.ToBoolean(dataGridView[preciosDataGridViewCheckBoxColumn.Index, e.RowIndex].Value);
            checkBoxVisit.Checked = Convert.ToBoolean(dataGridView[visitaDataGridViewCheckBoxColumn.Index, e.RowIndex].Value);
            checkBoxCopy.Checked = Convert.ToBoolean(dataGridView[copyDataGridViewCheckBoxColumn.Index, e.RowIndex].Value);
            textBoxComments.Text = dataGridView[comentariosDataGridViewTextBoxColumn.Index, e.RowIndex].Value.ToString();

            if (dataGridView[closeByUserDataGridViewTextBoxColumn.Index, e.RowIndex].Value == DBNull.Value)
                comboBoxCloseByUser.SelectedIndex = -1;
            else
                comboBoxCloseByUser.Text = dataGridView[closeByUserDataGridViewTextBoxColumn.Index, e.RowIndex].Value.ToString();
            labelUpdated.Text = dataGridView[updatedDataGridViewTextBoxColumn.Index, e.RowIndex].Value.ToString();
            labelInserted.Text = dataGridView[insertedDataGridViewTextBoxColumn.Index, e.RowIndex].Value.ToString();

            // Initializing ID variable
            _callID = Convert.ToInt64(dataGridView[ordenDataGridViewTextBoxColumn.Index, e.RowIndex].Value);

            // Re enable event handlers
            checkBoxSample.CheckedChanged += checkBoxRequets_CheckedChanged;
            checkBoxShipping.CheckedChanged += checkBoxRequets_CheckedChanged;
            checkBoxResult.CheckedChanged += checkBoxRequets_CheckedChanged;
            checkBoxVials.CheckedChanged += checkBoxRequets_CheckedChanged;
            checkBoxPromotional.CheckedChanged += checkBoxRequets_CheckedChanged;
            checkBoxPrices.CheckedChanged += checkBoxRequets_CheckedChanged;
            checkBoxVisit.CheckedChanged += checkBoxRequets_CheckedChanged;
            checkBoxCopy.CheckedChanged += checkBoxRequets_CheckedChanged;

            // Enable Controls
            EnabledControls(false);
            EnableButtonSave();
        }
        private void dataGridView_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            dataGridView.ClearSelection();
        }

        // Date Time Picker
        private void dateTimePickerFilterStart_ValueChanged(object sender, EventArgs e)
        {
            // Avoid overlap in dates.
            dateTimePickerFilterEnd.MinDate = dateTimePickerFilterStart.Value;

            RefreshCalls();
        }
        private void dateTimePickerFilterEnd_ValueChanged(object sender, EventArgs e)
        {
            // Avoid overlap in dates.
            dateTimePickerFilterStart.MaxDate = dateTimePickerFilterEnd.Value;

            RefreshCalls();
        }

        // Combo Boxes
        private void comboBoxOpenByUser_SelectionChangeCommitted(object sender, EventArgs e)
        {
            EnableButtonSave();
        }
        private void comboBoxDoctor_SelectionChangeCommitted(object sender, EventArgs e)
        {
            EnableButtonSave();
        }
        private void comboBoxFilters_SelectionChangeCommitted(object sender, EventArgs e)
        {
            RefreshCalls();

            // Refresh Save Button Status
            EnableButtonSave();
        }
        private void comboBoxFilter_KeyDown(object sender, KeyEventArgs e)
        {
            // Validations if is the Delete Key.
            if (!e.KeyCode.Equals(Keys.Delete)) return;

            // Declare Local Variable
            ComboBox comboBox = sender as ComboBox;

            // Check is is null.
            if (comboBox != null) comboBox.SelectedIndex = -1;

            // Update calls table
            RefreshCalls();
        }
        private void comboBoxForm_KeyDown(object sender, KeyEventArgs e)
        {
            // Validations if is Delete Key.
            if (!e.KeyCode.Equals(Keys.Delete)) return;

            // Declare Local Variable
            ComboBox comboBox = sender as ComboBox;

            // Check is is null.
            if (comboBox != null) comboBox.SelectedIndex = -1;
        }

        // Interface
        public void New()
        {}
        public void Save()
        {
            try
            {
                // Begin
                mdiParent.Begin();

                var tmpCallID = _callID;

                // Coding
                mdiParent.toolStripButtonSave.Enabled = false;
                queriesTableAdapter.InsertUpdateCalls
                (
                    ref _callID,
                    textBoxComments.Text.Trim(),
                    comboBoxOpenByUser.Text,
                    checkBoxSample.Checked,
                    checkBoxShipping.Checked,
                    checkBoxResult.Checked,
                    checkBoxVials.Checked,
                    checkBoxPromotional.Checked,
                    checkBoxPrices.Checked,
                    checkBoxVisit.Checked,
                    checkBoxCopy.Checked,
                    comboBoxDoctor.SelectedValue.ToString(),
                    string.IsNullOrEmpty(comboBoxCloseByUser.Text) ? null : comboBoxCloseByUser.Text
                );

                // Let the user know what's going on.
                mdiParent.SetMessage(MDIParent.MessageType.Successful, tmpCallID == null ? string.Format(Resources.MessageSuccessfulInsertCall, _callID) : string.Format(Resources.MessageSuccessfulUpdateCall, _callID));

                // Update number of calls.
                mdiParent.UpdateTodayCallsComplaints();

                // Refresh call
                RefreshCalls();

                // Reselect Row
                if (tmpCallID != null)
                {
                    var row = sPCALLSSELECTBindingSource.Find(dataSetSGLL.SP_CALLS_SELECT.OrdenColumn.Caption, _callID);
                    dataGridView.BeginInvoke((MethodInvoker) delegate
                    {
                        dataGridView.Rows[row].Selected = true;
                    });
                }

                // Clear form
                ClearForm();

                // Log File
            }
            catch (Exception exception)
            {
                // Report Error
                Utilities.ExceptionManager(exception);
            }
            finally
            {
                // End
                mdiParent.End();
            }
        }
        public void Print()
        {
            // Prevent future invocations to the print button.
            mdiParent.toolStripMenuItemPrint.Enabled = mdiParent.toolStripButtonPrint.Enabled = false;

            // Call preview form
            FormPrintPreview formPrintPreview = new FormPrintPreview(this, dataSetSGLL.SP_CALLS_SELECT, dateTimePickerFilterStart.Value, dateTimePickerFilterEnd.Value, FormPrintPreview.ReportTypes.Calls) { MdiParent = MdiParent, WindowState = FormWindowState.Maximized };
            formPrintPreview.Show();
        }
        public void SetControlBox()
        {
            // Toolbar button
            mdiParent.toolStripMenuItemClear.Enabled = mdiParent.toolStripButtonClear.Enabled = true;
            mdiParent.toolStripMenuItemPrint.Enabled = mdiParent.toolStripButtonPrint.Enabled = !dataGridView.Rows.Count.Equals(0);
            EnableButtonSave();

            mdiParent.toolStripMenuItemModeI.Visible = true;
            mdiParent.toolStripMenuItemModeII.Visible = true;
            mdiParent.toolStripMenuItemModeIII.Visible = true;
            mdiParent.toolStripMenuItemModeI.Checked = true;

            // Status bar
            mdiParent.toolStripStatusLabelShowAllCalls.Visible = mdiParent.toolStripStatusLabelNumberCallsFiltered.Visible = true;

            // Hooking up the binding source.
            mdiParent.toolStripMenu.BindingSource = sPCALLSSELECTBindingSource;
        }
        public void ClearFilter()
        {
            // Reset each control
            dateTimePickerFilterStart.Checked = dateTimePickerFilterEnd.Checked = false;
            comboBoxDoctorFilter.SelectedIndex =
                comboBoxOpenByUserFilter.SelectedIndex =
                comboBoxCloseByUserFilter.SelectedIndex =
                comboBoxRequestFilter.SelectedIndex = comboBoxRouteFilter.SelectedIndex = -1;

            // Call method
            RefreshCalls();
        }
        public void ClearForm()
        {
            // Variables
            _callID = null;
            
            // Clear selection on Combo Boxes.
            comboBoxDoctor.SelectedIndex = -1;
            comboBoxCloseByUser.SelectedIndex = -1;

            //CheckBoxes
            checkBoxSample.Checked = checkBoxShipping.Checked = checkBoxResult.Checked = checkBoxVials.Checked = checkBoxPromotional.Checked = checkBoxPrices.Checked = checkBoxVisit.Checked = checkBoxCopy.Checked = false;

            // Set inserted and updated date
            labelInserted.Text = labelUpdated.Text = string.Empty;

            // Clear cComments
            textBoxComments.Text = string.Empty;

            // Clear Data Grid View Selection
            dataGridView.ClearSelection();

            // Enable Controls
            EnabledControls(true);

            // Set focus
            buttonDoctor.Focus();
        }
        public void ChangeFormView(Global.FormViewModes mode)
        {
            switch (mode)
            {
                case Global.FormViewModes.ModeI:
                    splitContainer.Panel1Collapsed = false;
                    splitContainer.Panel2Collapsed = false;
                    break;
                case Global.FormViewModes.ModeII:
                    splitContainer.Panel1Collapsed = false;
                    splitContainer.Panel2Collapsed = true;
                    break;
                case Global.FormViewModes.ModeIII:
                    splitContainer.Panel1Collapsed = true;
                    splitContainer.Panel2Collapsed = false;
                    break;
            }
        }
        public void EnablePrintButton()
        {
            
        }
        public void Export()
        {
        }

        // General Purpose Functions
        private void RefreshCalls()
        {
            try
            {
                // Start process
                mdiParent.Begin();

                // Declare Local Variables
                DateTime? startDate, endDate;

                // Initializing Start and End Date variables.
                if (dateTimePickerFilterStart.Checked) startDate = dateTimePickerFilterStart.Value; else startDate = null;
                if (dateTimePickerFilterEnd.Checked) endDate = dateTimePickerFilterEnd.Value; else endDate = null;

                // Fill Table Adapter
                sP_CALLS_SELECTTableAdapter.Fill
                (
                    dataSetSGLL.SP_CALLS_SELECT,
                    startDate,
                    endDate,
                    comboBoxRouteFilter.SelectedValue == null ? null : comboBoxRouteFilter.Text,
                    comboBoxDoctorFilter.SelectedValue == null ? null : comboBoxDoctorFilter.Text,
                    comboBoxOpenByUserFilter.SelectedValue == null ? null : comboBoxOpenByUserFilter.Text,
                    comboBoxCloseByUserFilter.SelectedValue == null ? null : comboBoxCloseByUserFilter.Text,
                    comboBoxRequestFilter.SelectedIndex.Equals(0),
                    comboBoxRequestFilter.SelectedIndex.Equals(1),
                    comboBoxRequestFilter.SelectedIndex.Equals(2),
                    comboBoxRequestFilter.SelectedIndex.Equals(3),
                    comboBoxRequestFilter.SelectedIndex.Equals(4),
                    comboBoxRequestFilter.SelectedIndex.Equals(5),
                    comboBoxRequestFilter.SelectedIndex.Equals(6),
                    comboBoxRequestFilter.SelectedIndex.Equals(7)
                );

                // If more than one row was displayed on the grid then enable Print button.
                mdiParent.toolStripMenuItemPrint.Enabled = mdiParent.toolStripButtonPrint.Enabled = !dataGridView.Rows.Count.Equals(0);

                // Let the User Know, set up status bar
                mdiParent.toolStripStatusLabelNumberCallsFiltered.Text = string.Format(Resources.FilterStatusCalls, dataGridView.Rows.Count, queriesTableAdapter.GetTotalCalls());
                mdiParent.SetMessage(MDIParent.MessageType.Information, Resources.MessageSuccessfulCallSearch);
            }
            catch (Exception exception)
            {
                // Report Error
                Utilities.ExceptionManager(exception);
            }
            finally
            {
                // End process
                mdiParent.End();
            }
        }
        private void EnabledControls(bool value)
        {
            labelOpenByUser.Enabled =
            comboBoxOpenByUser.Enabled =
            comboBoxDoctor.Enabled =
            labelDoctor.Enabled =
            buttonDoctor.Enabled =
            labelRequests.Enabled =
            checkBoxSample.Enabled =
            checkBoxShipping.Enabled =
            checkBoxResult.Enabled =
            checkBoxVials.Enabled = 
            checkBoxPromotional.Enabled = 
            checkBoxPrices.Enabled = 
            checkBoxVisit.Enabled =
            checkBoxCopy.Enabled =
            checkBoxCopy.Enabled =
            labelDateTime.Enabled =
            labelInserted.Enabled =
            labelUpdated.Enabled = value;

            // Setting comments and closing user
            labelComments.Enabled =
            textBoxComments.Enabled =
            comboBoxCloseByUser.Enabled = comboBoxCloseByUser.SelectedIndex.Equals(-1);
        }
        private void EnableButtonSave()
        {
            mdiParent.toolStripButtonSave.Enabled = mdiParent.toolStripMenuItemSave.Enabled =
                !comboBoxOpenByUser.SelectedIndex.Equals(-1) &&
                (checkBoxSample.Checked || checkBoxShipping.Checked || checkBoxResult.Checked || checkBoxVials.Checked || checkBoxPromotional.Checked || checkBoxPrices.Checked || checkBoxVisit.Checked || checkBoxCopy.Checked) &&
                !comboBoxDoctor.SelectedIndex.Equals(-1);
        }
    }
}